<template>
  <view class="relative">
    <!-- 主题 -->
    <view class="theme" v-if="state.themeList.length > 0">
      <view ref="scrollView" class="scrollView">
        <text
		style="margin-right: 20rpx;"
          v-for="e in state.themeList"
          :key="e.topicId"
          :class="e.active ? 'active' : ''"
          @click="handleChooseTheme(e)"
        >
          {{ e.topicName }}
        </text>
      </view>
      <!-- 更多 -->
      <wd-img :src="ThemeMoreSvg" class="theme-more" @click="state.themeShowYn = true" />
    </view>
    <!-- 评论列表 -->
    <view class="comments">
      <Dynamic
        v-for="item in state.commentList"
        :key="item.id"
        :themeName="item.topicName"
        :imgList="item.picture"
        :avatar="item.headshot || defaultUserAvatar"
        :name="item.name"
        :propsUserId="item.userId"
        :publishTime="item.createTime"
        :content="item.content"
        :isLike="item.isLike"
        :likeNumber="item.likeCount"
        :chatNumber="item.commentCount"
        @clickDynamic="clickDynamic(item)"
        @clickUser="clickUser(item)"
        @clickThumbsup="clickThumbsup(item)"
        @clickChat="clickChat(item)"
        @clickDel="clickDel(item)"
        class="bg-[#fff]"
      ></Dynamic>
      <!-- 发布按钮 -->
      <wd-img
        v-if="!state.publishActionShowYn"
        :src="PublishSvg"
        class="publish"
        @click="state.publishActionShowYn = true"
      />
      <!-- 暂无动态 -->
      <view
        v-if="state.commentList.length === 0"
        class="empty-state flex-center flex-col mt-200rpx"
      >
        <wd-status-tip :image="emptyImage" tip="暂无动态" />
      </view>
    </view>
    <!-- 发布图文/发布文章 -->
    <view v-if="state.publishActionShowYn" class="mask">
      <view class="publish-view">
        <view @click="handlePublish('图文')">发图文</view>
        <view @click="handlePublish('文章')">发文章</view>
        <view class="bg-gray"></view>
        <view @click="state.publishActionShowYn = false">取消</view>
      </view>
    </view>
    <!-- 全部主题弹框 -->
    <wd-action-sheet v-model="state.themeShowYn" title=" " @close="state.themeShowYn = false">
      <view class="popup-theme">
        <text
          class="item-0"
          :class="state.myThemeList[0].active ? 'active' : ''"
          @click="handleChooseTheme(state.myThemeList[0])"
        >
          {{ state.myThemeList[0].topicName }}
        </text>
      </view>
      <view class="mx-30rpx mb-20rpx flex items-center justify-between">
        <text class="text-34rpx fw-700 text-[#3d3d3d]">我的主题</text>
        <view
          v-if="state.myThemeList.length > 11"
          class="text-24rpx text-[#CCCCCC]"
          @click="handleShowMore('showMyMoreYn')"
        >
          <text>查看更多</text>
          <wd-icon
            v-if="!state.showMyMoreYn"
            name="arrow-right"
            size="22rpx"
            color="#CCCCCC"
          ></wd-icon>
          <wd-icon v-else name="arrow-down" size="22rpx" color="#CCCCCC"></wd-icon>
        </view>
      </view>
      <view class="popup-theme">
        <view v-if="state.myThemeList.length > 1">
          <text
            v-for="e in state.myThemeList.slice(1, state.myMinLength)"
            :key="e.topicId"
            :class="e.active ? 'active' : ''"
            class="item"
            @click="handleChooseTheme(e)"
          >
            {{ e.topicName }}
          </text>
        </view>
        <text v-else class="item">暂无主题</text>
      </view>
      <view class="mx-30rpx mt-60rpx mb-20rpx flex items-center justify-between">
        <text class="text-34rpx fw-700 text-[#3d3d3d]">更多主题</text>
        <view
          v-if="state.moreThemeList.length > 10"
          class="text-24rpx text-[#CCCCCC]"
          @click="handleShowMore('showMoreYn')"
        >
          <text>查看更多</text>
          <wd-icon
            v-if="!state.showMoreYn"
            name="arrow-right"
            size="22rpx"
            color="#CCCCCC"
          ></wd-icon>
          <wd-icon v-else name="arrow-down" size="22rpx" color="#CCCCCC"></wd-icon>
        </view>
      </view>
      <view class="popup-theme">
        <view v-if="state.moreThemeList.length > 0" class="more-theme">
          <text
            v-for="e in state.moreThemeList.slice(0, state.moreMinLength)"
            :key="e.topicId"
            :class="e.active ? 'active' : ''"
            class="item"
            @click="handleChooseTheme(e)"
          >
            {{ e.topicName }}
          </text>
        </view>
        <text v-else class="item">暂无主题</text>
      </view>
    </wd-action-sheet>
  </view>
</template>

<script setup lang="ts">
import { useUserStore } from '@/store'

/* 引入 组件 */
import Dynamic from '@/uni_modules/comments/components/qizai-dynamic/Dynamic.vue'
import { useToast } from 'wot-design-uni'

/* 引入 图片 - 发布 */
import PublishSvg from '@/static/images/comment/publish.png'
/* 引入 图片 - 更多 */
import ThemeMoreSvg from '@/static/images/comment/theme-more.png'
/* 引入 图片 - 评论默认头像 */
import defaultUserAvatar from '@/static/images/comment/default_user.png'
/* 引入 暂无数据 - 图片 */
import emptyImage from '@/static/images/icons/empty.png'

/* 引入 mock 数据 */
import { themeList } from './config/index'

/* 引入 接口 */
import {
  addLike,
  cancelLike,
  deleteDiscussion,
  getCommentListApi,
  getThemeApi,
  hasNewMsgYnAPi,
} from '@/service/edu/comment/index'

import { msgReadStore } from '@/store/msgReadStatus'

const msgIsReadStore = msgReadStore()

const props = defineProps({
  searchValue: {
    type: String,
  },
})

const emit = defineEmits(['getHasNewMsgYn'])

/* 定义数据 */
const state = reactive({
  headshot: '', // 用户头像
  themeList: [], // 所有主题
  myThemeList: [], // 我的主题
  moreThemeList: [], // 更多主题
  commentList: [], // 评论列表
  publishActionShowYn: false, // 发布操作是否展示
  themeShowYn: false, // 全部主题弹框是否展示
  themeName: '', // 当前选中的主题名称
  myMinLength: 11, // 我的主题默认显示数量
  moreMinLength: 10, // 我的主题默认显示数量
  showMyMoreYn: false, // 我的主题是否展示更多
  showMoreYn: false, // 更多主题是否展示更多
})

/* 获取 主题 */
async function getThemeList() {
  const res: any = await getThemeApi({
    topicName: '',
  })
  if (res?.code === 200) {
    state.themeList = res?.rows || []
  }
  if (state.themeList.length > 0) {
    state.themeList.unshift({
      topicId: 'all',
      topicName: '全部',
      active: true,
    })
  }
}

/* 获取 我的主题 */
async function getMyThemeList() {
  const res: any = await getThemeApi({
    moreTopic: false,
  })
  if (res?.code === 200) {
    state.myThemeList = res?.rows || []
    if (state.themeList.length > 0) {
      state.myThemeList.unshift({
        topicId: 'all',
        topicName: '全部',
        active: true,
      })
    }
  }
}

/* 获取 更多主题 */
async function getMoreThemeList() {
  const res: any = await getThemeApi({
    moreTopic: true,
  })
  if (res?.code === 200) {
    state.moreThemeList = res?.rows || []
  }
}

/* 主题 - 展开更多 */
function handleShowMore(type: string) {
  state[type] = !state[type]
  if (type === 'showMyMoreYn') {
    state.myMinLength = state.showMyMoreYn ? state.myThemeList.length : 11
  } else {
    state.moreMinLength = state.showMoreYn ? state.moreThemeList.length : 10
  }
}

watch(
  () => props.searchValue,
  () => {
    getCommentList()
  },
)

/* 获取 评论列表 */
async function getCommentList() {
  const res: any = await getCommentListApi({
    content: props.searchValue || undefined,
    topicName: state.themeName === '全部' ? undefined : state.themeName,
  })
  if (res?.code === 200) {
    const { rows = [] } = res
    if (rows.length > 0) {
      state.commentList = rows
      state.commentList.forEach((e) => {
        if (e.picture) {
          if (typeof e.picture === 'string') {
            e.picture = e.picture.split(',')
          }
        } else {
          e.picture = []
        }
      })
    } else {
      state.commentList = []
    }
  } else {
    state.commentList = []
  }
}

/* 发布图文/发布文章 - 操作 */
function handlePublish(title: string) {
  state.publishActionShowYn = false
  uni.navigateTo({
    url: `/pages/comment/publish/index?title=${title}`,
  })
}

const scrollView = ref(null)
function scrollToText(item) {
  const arr = state.themeList.map((e) => e.topicName)
  const index = arr.indexOf(item.topicName)

  if (scrollView.value && index !== -1) {
    const textItem = scrollView.value.$el.children[index]

    const scrollLeft = textItem.offsetLeft

    scrollView.value.$el.scrollLeft = scrollLeft - 30
  }
}

/* 选择主题 */
async function handleChooseTheme(item: any) {
  state.themeName = item.topicName
  await getCommentList()
  state.themeShowYn = false
  state.themeList.forEach((e) => {
    e.active = false
    if (e.topicId === item.topicId) {
      e.active = true
    }
  })
  state.myThemeList.forEach((e) => {
    e.active = false
    if (e.topicId === item.topicId) {
      e.active = true
    }
  })
  state.moreThemeList.forEach((e) => {
    e.active = false
    if (e.topicId === item.topicId) {
      e.active = true
    }
  })
  scrollToText(item)
}

// onLoad(async () => {
//   await getThemeList()
//   await getCommentList()
// })

onShow(async () => {
  if (!msgIsReadStore.isRead) {
    const res = await hasNewMsgYnAPi()
    emit('getHasNewMsgYn', res.data)
    msgIsReadStore.setIsRead(res.data)
  }
  await getThemeList()
  await getCommentList()
  getMyThemeList()
  getMoreThemeList()
})

function clickDynamic(item) {
  console.log('childDynamic')
  uni.navigateTo({
    url: `/pages/comment/details/index?commentId=${item.id}`,
  })
}

// 点击用户信息
function clickUser(item) {
  console.log('childUser')
  uni.navigateTo({
    url: `/pages/comment/details/index?commentId=${item.id}`,
  })
}

// 点赞
const userStore = useUserStore()
const toast = useToast()
async function clickThumbsup(item: any) {
  for (const e of state.commentList) {
    if (e.id === item.id) {
      e.isLike = !e.isLike

      if (e.isLike) {
        e.likeCount++
        try {
          const res = await addLike({
            discussionId: item.id,
            likeType: 1, // 1为帖子，2为评论
            fromId: userStore.userInfo.userId, // 点赞人id
            toId: item.userId, // 被点赞人id
          })
          console.log(res, 'res')
          // if (res.code !== 200) {
          //   toast.error('点赞失败，请稍候重试~')
          //   await getCommentList()
          //   return
          // }
        } catch (error) {
          // 处理错误情况
          toast.error('点赞失败，请稍候重试~')
          console.error('Error handling like:', error)
          await getCommentList()
        }
      } else {
        e.likeCount--
        try {
          const res = await cancelLike({ someId: item.id, likeType: 1 })
          // if (res.code !== 200) {
          //   toast.error('点赞失败，请稍候重试~')
          //   await getCommentList()
          //   return
          // }
        } catch (error) {
          // 处理错误情况
          toast.error('点赞失败，请稍候重试~')
          console.error('Error handling like:', error)
          await getCommentList()
        }
      }
    }
  }
}

// 点击聊天
function clickChat(item) {
  console.log('clickChat')
  uni.navigateTo({
    url: `/pages/comment/details/index?commentId=${item.id}`,
  })
}

/* 删除 */
function clickDel(item) {
  uni.showModal({
    title: '提示',
    content: '确认要删除此条发布内容吗？',
    success: async (res) => {
      if (res.confirm) {
        console.log('用户点击确定')
        try {
          await deleteDiscussion(item.id)
          await getCommentList()
        } catch (e) {
          console.error('删除失败', e)
        } finally {
          // revertRef.value.close()
        }
      } else if (res.cancel) {
        console.log('用户点击取消')
      }
    },
  })
}
</script>

<style lang="scss" scoped>
/* 主题 */
.theme {
  // position: fixed;
  // top: 162rpx;
  // z-index: 9;
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  width: 100%;
  max-width: 100%;
  height: 100rpx;
  background-color: #f5f5f5;

  & > .scrollView {
    display: flex;
    flex: 1;
    flex-wrap: nowrap;
    // gap: 20rpx;
    padding: 20rpx;
    overflow-x: auto;

    & > text {
      padding: 8rpx 30rpx;
      font-size: 28rpx;
      font-weight: 700;
      color: #333;
      white-space: nowrap;
      background-color: #d8d8d8;
      border-radius: 10rpx;
    }

    & > text.active {
      color: #3670f7;
      background-color: #d3e2ff;
    }
  }
  /* 主题 - 隐藏滚动条 */
  & > .scrollView::-webkit-scrollbar {
    display: none;
  }

  .theme-more {
    width: 100rpx;
    height: 100rpx;
    background: linear-gradient(
      90deg,
      rgba(255, 255, 255, 0) 0%,

      rgba(255, 255, 255, 0.8) 14%,
      #ffffff 39%
    );
  }
}
/* 评论列表 */
.comments {
  max-height: calc(100vh - 280rpx);
  overflow: auto;
}
/* 发布图文/发布文章 */
.mask {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.7);

  .publish-view {
    position: absolute;
    bottom: 0;
    z-index: 999;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 100vw;
    background: #fff;

    view {
      width: 100vw;
      height: 100rpx;
      line-height: 100rpx;
      text-align: center;
      cursor: pointer;
      border-bottom: solid 1rpx #f5f5f8;
    }

    view:hover {
      background: #e0dfe2;
    }

    .bg-gray {
      height: 20rpx;
      background: #f2f2f6;
    }
  }
}
/* 主题弹出框 */
:deep(.wd-popup) {
  position: absolute;
  height: 90vh;
  border-radius: 0;
  .wd-action-sheet__close {
    position: absolute;
    right: 92%;
  }
}

.popup-theme {
  display: flex;
  flex-wrap: wrap;
  gap: 40rpx 30rpx;
  padding: 20rpx 30rpx;

  .more-theme {
    display: flex;
    flex-wrap: wrap;
    gap: 40rpx 30rpx;
  }
  .item-0 {
    padding: 8rpx 30rpx;
    font-size: 28rpx;
    font-weight: 700;
    color: #333;
    background-color: #d8d8d8;
    border-radius: 12rpx;
  }
  /* stylelint-disable-next-line no-descending-specificity */
  .item {
    max-width: 100%;
    padding: 8rpx 30rpx;
	margin-right: 20rpx;
    overflow: hidden;
    font-size: 28rpx;
    color: #333;
    text-overflow: ellipsis;
    white-space: nowrap;
    background-color: #d8d8d8;
    border-radius: 100rpx;
  }
  /* stylelint-disable-next-line no-descending-specificity */
  .item.active,
  .item-0.active {
    color: #3670f7;
    background-color: #d3e2ff;
  }
}
/* 主页 - 发布按钮 */
.publish {
  position: fixed;
  right: 20rpx;
  bottom: 120rpx;
  width: 120rpx;
  height: 120rpx;
}
</style>
